/**************************************
 *
 *       修改原common.js中的方法
 *
 ***************************************/
var commonFun = {
    //车辆树
    carTree: 1,
    //驾驶员树
    driverTree: 2,
    //线路树
    lineTree: 3,
    //左侧树节点点击事件对象
    leftTreeNodeClickObj: {},
    /**
     * 获取左侧机构树被勾选的节点
     * @param type 按节点类别获取的节点集合
     * @param original {boolean} 是否原生态返回节点数据
     *                    true返回的数据为{CAR:[选中的车辆节点集合],LINE:[选中的线路节点集合]},
     *                    否则就是{CAR:[选中的车辆ID集合],LINE:[选中的线路节点ID集合]}
     * @returns JSON
     */
    getLeftTreeCheckedNodes: function (type, original) {
        return window.parent.leftTreePulicMethod('getCheckedNodes', [type, original]);
    },
    /**
     * 获取左侧树被选中的节点数据集合
     * @returns {*}
     */
    getLeftTreeSelectedNodes: function () {
        return window.parent.leftTreePulicMethod('getSelectedNodes');
    },
    /**
     * 指定显示树
     * @param treeType 树的类别
     */
    showLeftTree: function (treeType) {
        window.parent.leftTreePulicMethod('showTree', [treeType]);
    },
    
    /**
     * 设置选中节点
     * @param tId 节点id
     */
    setSelectedNodes : function(tId){
    	window.parent.leftTreePulicMethod('setSelectedNodes', [tId]);
    },
    
    /**
     * 设置勾选节点
     * @param tId 节点id
     */
    setCheckedNodes : function(tId){
    	window.parent.leftTreePulicMethod('setCheckedNodes', [tId]);
    },
    
    /**
     * 获取指定类型节点
     * @param type 节点类型
     */
    getNodesByType : function(type){
    	return window.parent.leftTreePulicMethod('getNodesByType', [type]);
    },
    
    /**
     * 重新加载树
     */
    reloadLeftTree: function () {
        window.parent.leftTreePulicMethod('reload');
    },
    /**
     * 左侧树多选还是单选
     * @param boolEnable {boolean} true复选,false多选
     */
    changeLeftTreeCheckboxEnable: function (boolEnable) {
        window.parent.leftTreePulicMethod('changeCheckboxEnable', [boolEnable]);
    },
    /**
     * 获取左侧树当前树类型
     * @returns {*}
     */
    getLeftTreeCurrentTreeType: function () {
        return window.parent.leftTreePulicMethod('getCurrentTreeType');
    },
    /**
     * 设置左侧树车辆状态及图标
     */
    setCarStatus: function (carId, status) {
        window.parent.leftTreePulicMethod('setCarStatus', [carId, status]);
    },
    checkAllNodes: function (checked) {
        window.parent.leftTreePulicMethod('checkAllNodes', [checked]);
    },
    /**
     * 加载权限按钮
     * @param container jquery对象 权限按钮容器
     */
    authorityLoad: function (container) {
        var _cache = window.parent.GLOBAL_PARAMS.AUTHORITY_CACHE;
        $(container).find('[data-authority]').hide().each(function () {
            var authority = $(this).attr('data-authority');
            if (authority) {
                if (_cache.indexOf(authority) > -1) {
                    $(this).show().removeAttr('data-authority');
                }
            }
        });
    },

    /**
     * 刷新功能权限
     */
    refreshFuncAuth: function(){
        $.ajaxExt({
            url: '/sysAuthorityFunc/getCheckedFuncCache.htm',
            success: function (result) {
                if(result){
                    var cache = [];
                    $.each(result, function(index, item){
                        cache.push(item.id);
                    });
                    window.parent.GLOBAL_PARAMS.AUTHORITY_CACHE =  cache || [];
                }
            }
        });
    },

    /**
     * 在目标对象上面创建遮罩层
     * @param $target 目标jquery对象
     * @returns {*|jQuery} 返回遮罩层jquer对象
     */
    createLoadMask: function ($target) {
        var loadMask = $('<div><div class="loadMask-main"></div></div>').appendTo($target);
        $('<div class="loadMask-content" style="top:' + (loadMask.find('div').height() - 102) / 2 + 'px;' +
        'left:' + (loadMask.width() - 100) / 2 + 'px;">' +
        '<img src="' + $.getProjectName() + '/common/images/loading.gif"/>' + '</div>')
            .appendTo(loadMask);
        return loadMask;
    },
    /**
     * 根据时间类型及当前时间计算出开始与结束时间
     * @param timeType
     * @returns {{beginTime: Date, endTime: Date}}
     */
    getBeginEndTimeByType: function (timeType) {
        var beginTime = new Date(),
            endTime = new Date();
        var dd, cacheDate, q;
        switch (timeType) {
            case '02':
                DateExtend.dateAdd(beginTime, 'd', -1);
                endTime = beginTime;
                break;
            case '03':
                dd = beginTime.getDay() || 7;
                DateExtend.dateAdd(beginTime, 'd', 1 - dd);
                cacheDate = new Date(beginTime);
                endTime = DateExtend.dateAdd(cacheDate, 'd', 6);
                break;
            case '04':
                dd = beginTime.getDay() || 7;
                DateExtend.dateAdd(beginTime, 'd', 1 - dd);
                DateExtend.dateAdd(beginTime, 'd', -7);
                cacheDate = new Date(beginTime);
                endTime = DateExtend.dateAdd(cacheDate, 'd', 6);
                break;
            case '05':
                beginTime = new Date(beginTime.getFullYear(), beginTime.getMonth(), '1');
                endTime = new Date(endTime.getFullYear(), endTime.getMonth() + 1, '1');
                DateExtend.dateAdd(endTime, 'd', -1);
                break;
            case '06':
                beginTime = new Date(beginTime.getFullYear(), beginTime.getMonth() - 1, '1');
                endTime = new Date(endTime.getFullYear(), endTime.getMonth(), '1');
                DateExtend.dateAdd(endTime, 'd', -1);
                break;
            case '07':
                q = Math.ceil((beginTime.getMonth() + 1) / 3);
                beginTime = new Date(beginTime.getFullYear(), q * 3 - 3, '1');
                endTime = new Date(endTime.getFullYear(), q * 3, '1');
                DateExtend.dateAdd(endTime, 'd', -1);
                break;
            case '08':
                q = Math.ceil((beginTime.getMonth() + 1) / 3);
                beginTime = new Date(beginTime.getFullYear(), q * 3 - 3, '1');
                DateExtend.dateAdd(beginTime, 'm', -3);
                cacheDate = new Date(beginTime);
                endTime = DateExtend.dateAdd(cacheDate, 'm', 3);
                DateExtend.dateAdd(endTime, 'd', -1);
                break;
            case '11':
                beginTime = new Date(beginTime.getFullYear(), '0', '1');
                break;
            case '12':
                beginTime = new Date(beginTime.getFullYear() - 1, '0', '1');
                endTime = new Date(endTime.getFullYear() - 1, '11', '31');
                break;
        }
        return {
            beginTime: beginTime,
            endTime: endTime
        };
    },
    /**
     * 子界面弹出窗体统一调用此方法
     * @param options 窗体的配置信息
     * @returns {jQuery} 窗体对象
     */
    dialog: function (options) {
        var $div = $('<iframe frameborder="0" width="100%" height="100%;" src="{0}" style="display: none;"></iframe>'.format(options.url)).appendTo(window.parent.$('body'));

        commonFun._dialog.push($div);
        return window.parent.$.fn.dialog.call($div, options);
    },
    _dialog: [],//弹出的窗体统一保存到此数组中
    destroyDialog: function () {//销毁弹出的窗体
        $.each(commonFun._dialog, function (i, item) {
            if (item) {
                $(item).closest('.pop').remove();
            }
        });
    },
    execParentMethod: function (methodName) {
        var win = window.parent;
        var thisWin = window;
        var args = $.makeArray(arguments).slice(1);
        return win[methodName].apply(thisWin, args);
    },
    /**
     * 获取左侧树选中的人车线(复选)节点并转成key-value的形式返回出来
     * 如果没有选中的人车线节点会默认弹出提出消息（请选择查询车辆/机构/驾驶员）
     * 返回为空代表没有选中人车线节点
     * @returns {{driverIds: string, carIds: string, lineIds: string}}
     */
    getTreeCheckNodeToArgs: function () {
        var includeIds = false;//是否选择了节点
        var nodes = commonFun.getLeftTreeCheckedNodes();
        var obj = {
            driverIds: "",
            carIds: "",
            lineIds: ""
        };
        if (nodes.DRIVER) {//是否包含driverIds
            obj.driverIds = nodes.DRIVER;
            includeIds = true;
        }
        if (nodes.CAR) {//是否包含carIds
            obj.carIds = nodes.CAR;
            includeIds = true;
        }
        if (nodes.LINE) {//是否包含lineIds
            obj.lineIds = nodes.LINE;
            includeIds = true;
        }

        if (!includeIds) {
            $.messager.alert("提示", "请选择查询车辆/机构/驾驶员。", "info");
            return null;
        }
        return obj;
    }
};

//业务通用方法
(function () {
    window.business = {
        getLeftTreeSelectNode: function (nodeType) {

        },
        /**
         * 根据选中的左侧树节点来执行函数
         * @param {String} nodeType 节点类别（CAR、LINE、DRIVER）
         * @param fn
         */
        execFnByLeftTreeSelectNode: function (nodeType, fn) {
            var selectNode = commonFun.getLeftTreeSelectedNodes();
            if (selectNode.length) {
                var node = selectNode[0];
                if (nodeType && node.type !== nodeType) {
                    return;
                }
                fn('', node.tId.replace(/_\d+/, ''), node);
            }
        }
    };
})(jQuery);

/**************************************
 *消息弹出窗口
 *
 ***************************************/
(function ($) {
    if (window.parent.$.messager) {
        $.messager = window.parent.$.messager;
        return;
    }
})(jQuery);

(function () {
    window.history.forward(1);
    //处理键盘事件
    //禁止后退键（Backspace）密码或单行、多行文本框除外

    function banBackSpace(e) {

        var ev = e || window.event;//获取event对象

        var obj = ev.target || ev.srcElement;//获取事件源

        var t = obj.type || obj.getAttribute('type');//获取事件源类型

        //获取作为判断条件的事件类型

        var vReadOnly = obj.readOnly;

        var vDisabled = obj.disabled;

        //处理undefined值情况

        vReadOnly = (vReadOnly == undefined) ? false :
            vReadOnly;

        vDisabled = (vDisabled == undefined) ? true : vDisabled;

        //当敲Backspace键时，事件源类型为密码或单行、多行文本的，

        //并且readOnly属性为true或disabled属性为true的，则退格键失效

        var flag1 =
            ev.keyCode == 8 && (t == "password" ||
            t == "text" ||
            t == "textarea") &&
            (vReadOnly == true ||
            vDisabled == true);

        //当敲Backspace键时，事件源类型非密码或单行、多行文本的，则退格键失效

        var flag2 =
            ev.keyCode == 8 && t != "password" &&
            t != "text" &&
            t != "textarea";

        //判断
        if (flag2 || flag1) {
            return false;
        }

    }

    $(document).on('keypress', banBackSpace)
        .on('keydown', banBackSpace);

    //给按钮添加遮罩层防止多次点击
    $(document).on('click', '.btn-overlay', function () {
        var $div = $('<div>');
        $div.css({
            position: 'fixed',
            top: $(this).offset().top,
            left: $(this).offset().left,
            height: $(this).outerHeight(),
            width: $(this).outerWidth(),
            'z-index': 999999,
            cursor: 'pointer'
        }).appendTo($('body'));
        setTimeout(function () {
            $div.remove();
        }, 800);
    });
})();

/**************************************
 *自定义CanUI组件核心JS
 *
 ***************************************/
(function ($) {
    $.canui = function (name, config) {

        if ($.canui[name]) {
            return;
        }
        $.canui[name] = function () {
        };

        var _constructor = function (option, element, co) {
            this.options = $.extend({}, co, option);
            this._createWidget(element);
        };

        var base = {
            _createWidget: function (element) {
                this.element = $(element);
                this.widgetName = name;

                this._create();
                this._init();
            },
            _create: $.noop,
            _init: $.noop,
            option: function (key, value) {
                var options = key;
                if (arguments.length === 0) {
                    return this.options;
                }

                if (typeof key === "string") {
                    options = {};
                    options[key] = value;
                }
                this._setOptions(options);

                return this;
            },
            _setOptions: function (options) {
                var key;

                for (key in options) {

                    this._setOption(key, options[key]);
                }

                return this;
            },
            _setOption: function (key, value) {
                this.options[key] = value;
                return this;
            }
        };

        var parent = {};
        if (config.extend) {
            parent = (new $.canui[config.extend]());
        }

        $.canui[name].prototype = _constructor.prototype = $.extend({}, base, parent, config);


        $.fn[name] = function (pin) {

            if (typeof pin === 'string') {

                var instance = $.data(this[0], name);
                if ($.canui[name].prototype[pin]) {
                    var args = $.makeArray(arguments).slice(1);
                    if (this.length > 1) {
                        this.each(function () {
                            $.canui[name].prototype[pin].apply($.data(this, name), args);
                        });
                    } else {
                        return $.canui[name].prototype[pin].apply(instance, args);
                    }
                } else {
                    throw ("组件:" + name + " - 没有该方法: " + pin);
                }
            } else {
                return this.each(function () {
                    var instance = new _constructor(pin, this, config.options);

                    $.data(this, name, instance);
                });
            }
        };

    };
    $.fn.dialog = function (pin) {

        if (typeof pin === 'string') {
            var instance = window.parent.$.data(this[0], 'dialog');
            var args = $.makeArray(arguments).slice(1);
            return window.parent.$.canui.dialog.prototype[pin].apply(instance, args);
        } else {
            var $div = $('<iframe frameborder="0" width="100%" height="100%;" src="{0}" style="display: none;"></iframe>').appendTo(window.parent.$('body'));
            $div.attr('src', pin.url);

            var win = window;
            $div.one('load.opener', function () {
                this.contentWindow.opener = win;
                this.contentWindow.__closeSelf = function(){

                    $div.dialog('close');
                }
            });

            commonFun._dialog.push($div);
            return window.parent.$.fn.dialog.call($div, pin);
        }
    };

}(jQuery));

//分页
(function ($) {
    $.canui('createPage',{
        options:{
            pageCount: 10,
            current: 1,
            backFn: $.noop
        },
        _init: function () {
            this._fillHtml();
            this._bindEvent();
        },
        _fillHtml:function(){
            var obj = this.element,
                args = this.options;
            obj.empty();
            //上一页
            if (args.current > 1) {
                obj.append('<a class="prev">上一页</a> ');
            } else {
                obj.remove('.prev');
            }
            //中间页码
            if (args.current != 1 && args.current >= 4 && args.pageCount != 4) {
                obj.append('<a class="tcdNumber">' + 1 + '</a> ');
            }
            if (args.current - 2 > 2 && args.current <= args.pageCount && args.pageCount > 5) {
                obj.append('<a>...</a> ');
            }
            var start = args.current - 2, end = args.current + 2;
            if ((start > 1 && args.current < 4) || args.current == 1) {
                end++;
            }
            if (args.current > args.pageCount - 4 && args.current >= args.pageCount) {
                start--;
            }
            for (; start <= end; start++) {
                if (start <= args.pageCount && start >= 1) {
                    if (start != args.current) {
                        obj.append('<a class="tcdNumber">' + start + '</a> ');
                    } else {
                        obj.append('<a class="active">' + start + '</a> ');
                    }
                }
            }
            if (args.current + 2 < args.pageCount - 1 && args.current >= 1 && args.pageCount > 5) {
                obj.append('<a>...</a> ');
            }
            if (args.current != args.pageCount && args.current < args.pageCount - 2 && args.pageCount != 4) {
                obj.append('<a class="tcdNumber">' + args.pageCount + '</a> ');
            }
            //下一页
            if (args.current < args.pageCount) {
                obj.append('<a class="next">下一页</a> ');
            } else {
                obj.remove('.next');
            }
        },
        _bindEvent:function(){
            var obj = this.element,
                args = this.options;
            obj.on("click", "a.tcdNumber", function () {
                var current = parseInt($(this).text());
                args.current = current;
                args.pageCount = args.pageCount;
                args.backFn(current);
            });
            //上一页
            obj.on("click", "a.prev", function () {
                var current = parseInt(obj.children(".active").text());
                args.current = current - 1;
                args.pageCount = args.pageCount;
                args.backFn(args.current);
            });
            //下一页
            obj.on("click", "a.next", function () {
                var current = parseInt(obj.children(".active").text());
                args.current = current + 1;
                args.pageCount = args.pageCount;
                args.backFn(args.current);
            });
        }
    });
})(jQuery);